/* @(#)DBConnectionManager.java
 *
 * Project: BUSOrder
 *
 * Modify Information:
 * =============================================================================
 *   Author       Date       Description
 *   ------------ ---------- ---------------------------------------------------
 *   Simonyi Peng 2006-02-06 建立
 *   Janus   Liu  2007-05-22 增加数据库连接测试方法
 *
 * Copyright Notice:
 * =============================================================================
 *    Copyright (c) 2001-2007 Auto-Parts E-Procurement Co., Ltd. 
 *        No.251-1 Wuning Road, Shanghai, 200063, China All rights reserved.
 *
 *    This software is the confidential and proprietary information of
 *        Auto-Parts E-Procurement Co., Ltd. ("Confidential Information").
 *        You shall not disclose such Confidential Information and shall use it
 *        only in accordance with the terms of the license agreement you entered
 *        into with APEP.
 *
 * Warning:
 * =============================================================================
 * 
 */

package com.hitrust.gs.lib.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.hitrust.gs.lib.*;

import framework.core.Config;

/**
 * CUPSecure系统数据库连接管理类
 */
public class DBConnectionManager {
    
    private boolean iTrxInitialed = false;
    
    private boolean iTrxInitialedWeblogic = false;
    
    private DataSource iTrxDataSource = null;
    
    
    
    private static DBConnectionManager sUniqueInstanceOfDBConnectionManager = null;

    /**
     * 默认构造方法
     * @throws java.util.MissingResourceException
     */
    private DBConnectionManager() {
        initialDataSource();
    }

    /**
     * 取得CUPSecure系统数据库连接管理类实例
     * @return CUPSecure系统数据库连接管理类实例
     */
    public static synchronized DBConnectionManager getInstance() {
        if (sUniqueInstanceOfDBConnectionManager == null)
            sUniqueInstanceOfDBConnectionManager = new DBConnectionManager();
        
        return sUniqueInstanceOfDBConnectionManager;
    }
    
    /**
     * 初始化系统交易数据库数据源
     */
    private void initialDataSource() 
    {
    	//resin , tomcat , weblogic 
    	
//		String dataSource = GSSystemConfigurator.getParam("gs.DataSource");
//		String webServer = GSSystemConfigurator.getParam("gs.WebServer");
		try
		{
		    String dataSource = Config.getDBDataSource();
	        String webServer = Config.getWebServerType();
			if("resin".equalsIgnoreCase(webServer))
			{
				Context initCtx = new InitialContext();
				Context ctx = (Context) initCtx.lookup("java:comp/env");
				iTrxDataSource = (javax.sql.DataSource) ctx.lookup(dataSource); 
				iTrxInitialed = true;
			}
			else if("tomcat".equalsIgnoreCase(webServer))
			{
				Context initCtx = new InitialContext();
				Context ctx = (Context) initCtx.lookup("java:comp/env");
				iTrxDataSource = (javax.sql.DataSource) ctx.lookup(dataSource); 
				iTrxInitialed = true;
								
			}
			else if("WebLogic".equalsIgnoreCase(webServer))
			{
				iTrxDataSource = (DataSource)(new InitialContext()).lookup(dataSource);  //生产系统
				iTrxInitialedWeblogic = true;
			}
			else
			{
				throw new Exception("不能识别的WEB服务器:"+webServer);
			}
		}
		catch(Exception e)
		{
			GSLogWriter.fatal("无法初始化系统交易数据库数据源," + e.getMessage());
			e.printStackTrace();
		}
		/*
        String tNamingFactory = System.getProperty("java.naming.factory.initial");
        try
        {
        	 if (tNamingFactory.indexOf("org.apache.naming") >= 0) {
                //Tomcat
                //Context initContext = new InitialContext();
                //Context envContext  = (Context)initContext.lookup("java:comp/env");
                //oracle.jdbc.pool.OracleDataSource ds = (oracle.jdbc.pool.OracleDataSource )envContext.lookup("jdbc/gs");
                

            	Context initCtx=new InitialContext(); 
                DataSource ds=(DataSource)initCtx.lookup("java:comp/env/jdbc/gs");

                iTrxDataSource = ds;
                iTrxInitialed = true;
            }
            else 
            {
                initialDataSourceWeblogic();
            }
        }
        catch(Exception e){
            GSLogWriter.fatal("无法初始化系统交易数据库数据源," + e.getMessage());
            e.printStackTrace();
        }
        */
	}
    
    private void initialDataSourceWeblogic(){
		try
		{
			String ds = GSSystemConfigurator.getParam("gs.DataSource");
            iTrxDataSource = (DataSource)(new InitialContext()).lookup(ds);  //生产系统
            //iTrxDataSource = (DataSource)(new InitialContext()).lookup("gs");   //测试系统
            iTrxInitialedWeblogic = true;
		}
	    catch(Exception e){
	        GSLogWriter.fatal("无法初始化Weblogic系统交易数据库数据源");
	    }
    }


    /**
     * 取得交易数据库连接
     * @return 数据库连接
     * @throws SQLException 取得数据库连接是发生异常
     */
    public Connection getConnection() throws SQLException {
        if (!iTrxInitialed && !iTrxInitialedWeblogic) {
            throw new SQLException("系统交易数据库数据源未初始化");
        }
        
        Connection tConnection = null;
        if (iTrxInitialed){
            //tConnection = iTrxDataSource.getConnection("gsdev","123456");            
        	tConnection = iTrxDataSource.getConnection();
        }
        else if(iTrxInitialedWeblogic)
        {
        	int count = 0 ;
        	for(;;)
			{
				tConnection = iTrxDataSource.getConnection();
            	if(tConnection!=null&&!tConnection.isClosed()) break ;
            	try
            	{
					Thread.sleep(100);
					count ++ ;
					if(count>50)
					{
						GSLogWriter.debug("getConnection try 50 times error");
						break ;
					}
            	}
            	catch(Exception e)
            	{
					GSLogWriter.debug("getConnection"+e);
            	}
         	}
        }
        MyConnection con = new MyConnection(tConnection) ;
        con.setAutoCommit(true);
        //tConnection.setAutoCommit(true);
        return con;
    }
    
    /**
     * 释放数据库连接
     * @param aConnection 要进行释放的连接
     * @throws MissingResourceException
     */
    public static void releaseConnection(Connection aConnection) {
        if (aConnection == null)
            return;
        
        try {
            aConnection.close();
        }
        catch (Exception e) {
        }
    }
    
    /**
     * 测试数据库连接
     * @param aConnection 已有的数据库连接。传入null的话，本方法将会自动取得一个新的连接来进行测试。
     * @param aTableName 进行测试的数据库表格名称
     * @throws true: 正常  false: 异常
     */
    public boolean testConnection(Connection aConnection, String aTableName) {
        boolean tTestResult = false;
        
        Connection tConnection = aConnection;
        ResultSet  tRs = null;
        PreparedStatement tPstmt = null;
        try {
            if (tConnection == null) {
                tConnection = getConnection();
            }
            
            tPstmt = aConnection.prepareStatement("SELECT COUNT(*) FROM " + aTableName);
            tRs = tPstmt.executeQuery();
            
            tTestResult = true;
        }
        catch (Exception e) {
        }
        finally {
            if (tRs != null) {
                try {
                    tRs.close();
                } catch (SQLException ex) {
                }
            }
            if (tPstmt != null) {
                try {
                    tPstmt.close();
                } catch (SQLException ex) {
                }
            }
            releaseConnection(tConnection);
        }

        return tTestResult;
    }
    
    public static void main(String[] arg){
    	try{
    		DBConnectionManager tDBConnectionManager = DBConnectionManager.getInstance();
    		Connection conn = tDBConnectionManager.getConnection();
    		if(conn == null){
    			throw new Exception();
    		}else{
    			GSLogWriter.debug("true...");
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
}
